package ui;// LoginFrame.java
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import security.auth.UserManager;
import session.Session;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;

    public LoginFrame() {
        setTitle("DBMS 登录");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 200);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        panel.add(new JLabel("用户名:"));
        usernameField = new JTextField();
        panel.add(usernameField);

        panel.add(new JLabel("密码:"));
        passwordField = new JPasswordField();
        panel.add(passwordField);

        JButton loginButton = new JButton("登录");
        loginButton.addActionListener(new LoginAction());
        panel.add(loginButton);

        JButton registerButton = new JButton("注册");
        registerButton.addActionListener(e -> new RegisterDialog(this));

        panel.add(registerButton);

        add(panel);
        setVisible(true);
    }

    class LoginAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());

            // 调用 UserManager 进行登录验证
            Session session = UserManager.login(username, password);

            if (session != null) {
                // 激活会话
                session.activate();

                // 获取权限级别
                int level = session.getUserLevel();
                String levelStr = (level == UserManager.ADMIN_LEVEL) ? "管理员" : "普通用户";

                // 显示登录成功信息
                JOptionPane.showMessageDialog(
                    LoginFrame.this,
                    "登录成功！欢迎回来，" + username + " (" + levelStr + ")",
                    "登录成功",
                    JOptionPane.INFORMATION_MESSAGE
                );

                dispose();
                new MainFrame(username);
            } else {
                JOptionPane.showMessageDialog(
                    LoginFrame.this,
                    "登录失败，请检查:\n1. 用户名是否正确\n2. 密码是否正确\n3. 用户是否已注册",
                    "登录错误",
                    JOptionPane.ERROR_MESSAGE
                );
                passwordField.setText("");
            }
        }
    }
}
